﻿Namespace Catalog.Search
    ''' <summary>
    ''' The chart call is used to retrieve chart data.
    ''' </summary>
    Public Class ChartsQuery
        Inherits Query
        ''' <summary>
        ''' Filter charts by a list of numeric ids.
        ''' </summary>
        Public Property Ids As List(Of Integer)

        ''' <summary>
        ''' Which facets to apply to the chart catalog call.
        ''' </summary>
        Public Property Filters As Dictionary(Of QueryFilter, String)

        ''' <summary>
        ''' Which facets to return for possible later filtering.
        ''' </summary>
        Public Property ReturnFilters As List(Of QueryFilter)

        Public Sub New()
            MyBase.New()
            Me.Ids = New List(Of Integer)
            Me.Filters = New Dictionary(Of QueryFilter, String)()
            Me.ReturnFilters = New List(Of QueryFilter)()
        End Sub

        Public Sub New(id As Integer)
            Me.New()
            Me.Ids.Add(id)
        End Sub

        Public Sub New(ids As IEnumerable(Of Integer))
            Me.New()
            Me.Ids.AddRange(ids)
        End Sub

        Public Overrides Function GetUrl() As System.Uri
            Dim url As String = Beatport.CATALOG_CHARTS_URL
            Dim queryStr As New List(Of String)

            If Me.Ids.Count > 0 Then
                queryStr.Add(String.Format("id{0}={1}", If(Me.Ids.Count > 1, "s", ""), String.Join(",", Me.Ids.ToArray)))
            End If

            If Me.PageSize > 0 Then
                queryStr.Add(String.Format("perPage={0}&page={1}", Me.PageSize, Me.Page))
            End If

            If Me.Sort.Count > 0 Then
                Dim sortFields As New List(Of String)

                For Each sortField In Me.Sort
                    sortFields.Add(String.Format("{0}{1}", sortField.Field.ToString, If(sortField.SortDir = QuerySortDirection.descending, " desc", "")))
                Next

                queryStr.Add("sortBy=" & String.Join(",", sortFields.ToArray))
            End If

            If Me.ReturnFilters.Count > 0 Then
                queryStr.Add("returnFacets=" & String.Join(",", Me.ReturnFilters.ToArray))
            End If

            If Me.Filters.Count > 0 Then
                Dim filters As New List(Of String)

                For Each fil In Me.Filters
                    filters.Add(String.Format("facets[]={0}:{1}", fil.Key.ToString, fil.Value))
                Next

                queryStr.Add(String.Join("&", filters.ToArray))
            End If

            If queryStr.Count > 0 Then
                url = String.Format("{0}?{1}", url, String.Join("&", queryStr.ToArray))
            End If

            Return New Uri(url)
        End Function
    End Class
End Namespace